package com.leff.cards;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.leff.cards.data.AppState;
import com.leff.cards.util.Secrets;
import com.leff.cards.web.QueryDispatcher;
import com.leff.cards.web.requests.GcmRegisterRequest;
import com.leff.cards.web.requests.GcmUnregisterRequest;

public class GCMIntentService extends GCMBaseIntentService implements Secrets {

	@Override
	protected void onRegistered(Context C, String regId) {
		Log.v(Secrets.TAG, "Registered Device: " + regId);
		
		try {
			long id = AppState.get().getUser().id;
			new QueryDispatcher(new GcmRegisterRequest(id, regId)).execute();
		} catch(Exception e) {
			Log.v(Secrets.TAG, "No AppState available to pull user and send request!");
		}
	}

	@Override
	protected void onMessage(Context C, Intent I) {
		Log.v(Secrets.TAG, "GCM Message: " + I.getAction());
		
		Bundle B = I.getExtras();
		NotificationFactory.buildNotif(this, B);
	}

	@Override
	protected void onUnregistered(Context C, String regId) {
		Log.v(Secrets.TAG, "Unregistered Device: " + regId);

		try {
			long id = AppState.get().getUser().id;
			new QueryDispatcher(new GcmUnregisterRequest(id, regId)).execute();
		} catch(Exception e) {
			Log.v(Secrets.TAG, "No AppState available to pull user and send request!");
		}
	}

	@Override
	protected void onError(Context C, String errorId) {
		Log.v(Secrets.TAG, "GCM Error: " + errorId);
		
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		Log.v(Secrets.TAG, "GCM Recoverable Error: " + errorId);
		return super.onRecoverableError(context, errorId);
	}
}
